﻿using System;
using System.Reflection;
using Microsoft.Practices.CompositeUI.Commands;
using Microsoft.Practices.CompositeUI.EventBroker;
using Microsoft.Practices.ObjectBuilder;

namespace Microsoft.Practices.CompositeUI.BuilderStrategies
{
    /// <summary>
    /// 	A <see cref = "BuilderStrategy" /> that processes commands associated 
    /// 	with component members through the <see cref = "CommandHandlerAttribute" />.
    /// </summary>
    public class CommandStrategy : BuilderStrategy
    {
        #region Build Up

        /// <summary>
        /// 	See <see cref = "IBuilderStrategy.BuildUp" /> for more information.
        /// </summary>
        public override object BuildUp(IBuilderContext context, Type typeToBuild, object existing, string idToBuild)
        {
            var workItem = GetWorkItem(context, existing);
            if (workItem != null)
            {
                EventInspector.Register(existing, workItem);
            }
            return base.BuildUp(context, typeToBuild, existing, idToBuild);
        }

        #endregion

        #region Tear Down

        /// <summary>
        /// 	See <see cref = "IBuilderStrategy.TearDown" /> for more information.
        /// </summary>
        public override object TearDown(IBuilderContext context, object item)
        {
            var workItem = GetWorkItem(context, item);
            if (workItem != null)
            {
                EventInspector.Unregister(item, workItem);
            }
            return base.TearDown(context, item);
        }

        #endregion

        #region Get WorkItem

        private static WorkItem GetWorkItem(IBuilderContext context, object item)
        {
            if (item is WorkItem)
            {
                return item as WorkItem;
            }
            return context.Locator.Get<WorkItem>(new DependencyResolutionLocatorKey(typeof (WorkItem), null));
        }

        #endregion

        #region Register & Unregister Command Handlers

        private void RegisterCommandHandlers(IBuilderContext context, WorkItem workItem, object target, string targetID, MethodInfo methodInfo)
        {
            foreach (CommandHandlerAttribute attr in methodInfo.GetCustomAttributes(typeof(CommandHandlerAttribute), true))
            {
                Command cmd = workItem.Commands[attr.CommandName];

            }
        }

        #endregion
    }
}